/**
 * IScrollList使用说明：
 * param 对象
 * param.wrap iscrollwrap（外层的div，视域）
 * param.onLoadData  上拉请求更多数据回调
 * param.bindEvent  绑定事件(函数)
 *
 * @dependency jquery
 * @author Keith
 */
 /*global define window document navigator iScroll :true*/
define([
    "jquery", "iscroll"
], function($) {
    function IScrollList(param) {
        this.params = $.extend({
            wrap: null,
            bindEvent: null,
            onRefresh: null,
            onLoadData: null
        }, param);

        this.dataOffset = 0;
        this.statusFlag = 0; // 0:静态初始状态 1:正在加载中 2:加载完成状态
        this.myScroll;
        this.$container;
        this.$wrapper;
        this.$content;
        this.$html;
        this.$pullDownEl;
        this.$pullUpEl;

        this.cacheArea = $(window).height(); // 单位像素

        this._initDate();
        this._initUI();
        this._initIscroll();

        this._enablePullup = true;
    }

    IScrollList.prototype.getScroller = function() {
        return this.$content;
    };

    IScrollList.prototype.getContent = function() {
        return this.$html;
    };

    IScrollList.prototype.clearContent = function() {
        if (this.$html) {
            this.$html.html("");
            this.dataOffset = 0;
        }
    };

    IScrollList.prototype.disablePullUp = function() {
        this._enablePullup = false;
    };

    IScrollList.prototype.getDataOffset = function() {
        return this.dataOffset;
    };

    IScrollList.prototype.setDataOffset = function(dataOffset) {
        this.dataOffset = dataOffset;
    };

    IScrollList.prototype.resetDataOffset = function() {
        this.dataOffset = 0;
    };

    IScrollList.prototype.appendItem = function(dom) {
        this.$html.append(dom);
        if (this.params.bindEvent) {
            this.params.bindEvent.call(this);
        }
    };

    IScrollList.prototype.appendFinish = function() {
        var _this = this;

        // 强制刷新html
        _this.$content.hide().show(0);

        //设置正确的viewport高度
        _this.$content.height(_this.$html.height());
        _this.hidemsg();
        _this.myScroll.refresh();
    };

    IScrollList.prototype.clearItem = function(dom) {
        this.$content.html("");
    };

    /**
	 * 初始化参数和数据
	 */
    IScrollList.prototype._initDate = function() {
        if (!this.params.wrap) {
            console.error("wrap参数未指定");
            return;
        }
    };

    IScrollList.prototype._initUI = function() {
        var _this = this;

        _this.$wrapper = $("<div style='width: 100%;'><div/>");
        _this.$container = $("#" + _this.params.wrap);
        _this.$container.append(_this.$wrapper);

        _this.$pullDownEl = $("<div class='pullDown'></div>");
        _this.$pullUpEl = $("<div class='pullUp'></div>");
        _this.$content = $("<div class='scroller'></div>");
        _this.$container.append(_this.$content);
        _this.$html = $("<div style='width:100%; float:left;'></div>");
        _this.$content.append(_this.$html);
        _this.$wrapper.append(_this.$pullDownEl).append(_this.$content).append(_this.$pullUpEl);

        if (_this.$container.height() > _this.$content.height()) {
            _this.$content.css({
                "min-height": (_this.$container.height() - _this.$pullUpEl.height()) + "px"
            });
        }
        //_this.showmsg("加载数据中...");
        _this.showmsg("");
    };

    IScrollList.prototype._initIscroll = function() {
        var _this = this;
        var pullDownEl = _this.$pullDownEl.get(0);
        var pullUpEl = _this.$pullUpEl.get(0);
        var topOffset = _this.$pullDownEl.height() == 0
            ? 0
            : _this.$pullDownEl.height();
        _this.myScroll = _this.touchScroll(_this.params.wrap, {
            topOffset: topOffset,
            vScrollbar: false,
            onRefresh: function() {
                if (pullDownEl.className.match('loading')) {
                    pullDownEl.className = 'pullDown';
                } else if (pullUpEl.className.match('loading')) {
                    pullUpEl.className = 'pullUp';
                }
                this.enable();
            },
            onScrollMove: function() {
                if (this.y > 5 && !pullDownEl.className.match('flip')) {
                    pullDownEl.className = 'pullDown flip';
                    this.minScrollY = 0;
                } else if (this.y < 5 && pullDownEl.className.match('flip')) {
                    pullDownEl.className = 'pullDown';
                    this.minScrollY = -_this.$pullDownEl.get(0).offsetHeight;
                } else if (this.y < (this.maxScrollY - 5) && !pullUpEl.className.match('flip') && pullUpEl.className.indexOf("loading") < 0) {
                    pullUpEl.className = 'pullUp flip';
                    this.maxScrollY = this.maxScrollY;
                } else if (this.y > (this.maxScrollY + 5) && pullUpEl.className.match('flip')) {
                    pullUpEl.className = 'pullUp';
                    this.maxScrollY = _this.$pullUpEl.get(0).offsetHeight;
                }
                _this.$content.trigger("scroll");
            },
            onScrollEnd: function() {
                if (pullDownEl.className.match('flip')) {
                    pullDownEl.className = 'pullDown loading';
                    _this._pullDownAction();
                } else if (pullUpEl.className.match('flip') && pullUpEl.className.indexOf("loading") < 0) {
                    if (_this._enablePullup) {
                        pullUpEl.className = 'pullUp loading';
                        _this._pullUpAction();
                    } else {
                        pullUpEl.className = 'pullUp';
                    }
                }
                _this.$content.trigger("scroll");
            }
        });
        _this._pullUpAction();
    };

    IScrollList.prototype.touchScroll = function(elem, options) {
        if (typeof(elem) == "object") {
            elem = elem[0];
        }
        // 处理滚动手势
        options = options || {};
        //惯性
        options.momentum = true;
        options.handleClick = true;
        options.useTransition = this._isTransition();
        if (/iphone/.test(navigator.userAgent.toLowerCase())) {
            options.useTransition = true;
        }
        if (!options.hasOwnProperty("checkDOMChanges"))
            options.checkDOMChanges = false;
        if (!options.hasOwnProperty("hideScrollbar"))
            options.hideScrollbar = true;
        options.scrollbarClass = options.scrollbarClass || 'myScrollbar';
        options.onBeforeScrollStart = function(e) {
            if (this.absDistX > (this.absDistY + 5)) {
                e.preventDefault();
            }
        };
        options.onTouchEnd = function(e) {
            var self = this;
            if (self.touchEndTimeId) {
                clearTimeout(self.touchEndTimeId);
            }
            self.touchEndTimeId = setTimeout(function() {
                self.absDistX = 0;
                self.absDistY = 0;
            }, 600);
        };

        // FIXME 强制设置android机器的useTransition为false，以修正个别手机webview上对于topbar的兼容性问题
        // 暂时没有办法分辨手机兼容性，不使用transition会导致滚动性能降低
        if (/iphone/.test(navigator.userAgent.toLowerCase())) {
            options.useTransition = true;
        } else {
            options.useTransition = false;
        }

        return new iScroll(elem, options);
    };

    /**
	 * 显示信息
	 * @param msg
	 */
    IScrollList.prototype.showmsg = function(msg) {
        /*if($("#list_showmsg").length != 0) {
			return;
		}
		var _this = this;
		var msgView = $("<div id='list_showmsg' style=''></div>");
		msgView.text(msg);
		msgView.css({
			"position": "absolute",
			"top": "0",
			"left": "0",
			"line-height": _this.$container.height() + "px",
			"text-align": "center",
			"width": "100%",
			"height": _this.$container.height() + "px",
			"color": "#fff",
			"background-color": "rgba(0, 0, 0, 0.4)" ,
			"font-size:":"13px"
		});
		_this.$container.append(msgView);*/
    };

    /**
	 * 隐藏信息
	 */
    IScrollList.prototype.hidemsg = function() {
        //$("#list_showmsg").remove();
        this._changeStatus(2);
        if (!this.myScroll.enabled) {
            this.myScroll.enable();
        }
        this.myScroll.refresh();
    };

    IScrollList.prototype.scrollToEnd = function() {
        this.myScroll.scrollToElement(this.$content.children().last().get(0), 0);
    };

    // 辅助函数begin
    /**
	 * 上拉
	 */
    IScrollList.prototype._pullUpAction = function() {
        if (this._isLoading()) {
            return;
        }
        //this.showmsg("加载数据中...");
        this.showmsg("");
        this.myScroll.disable();
        this._changeStatus(1);
        if (this.params.onLoadData && typeof this.params.onLoadData == "function") {
            this.params.onLoadData.apply(this, [this.dataOffset]);
        }
    };

    IScrollList.prototype._pullDownAction = function() {
        if (this._isLoading()) {
            return;
        }
        this.refresh();
    };

    IScrollList.prototype.refresh = function() {
        this._enablePullup = true;
        //this.showmsg("加载数据中...");
        this.showmsg("");
        this.myScroll.disable();
        this._changeStatus(1);
        if (this.params.onRefresh && typeof this.params.onRefresh == "function") {
            this.params.onRefresh.apply(this);
        }
        this.dataOffset = 0;
        this.$html.html("");
        if (this.params.onLoadData && typeof this.params.onLoadData == "function") {
            this.params.onLoadData.apply(this, [this.dataOffset]);
        }
    };

    IScrollList.prototype._isLoading = function() {
        return this.statusFlag == 1;
    };

    IScrollList.prototype._changeStatus = function(status) {
        this.statusFlag = status;
    };

    IScrollList.prototype._isTransition = function() {
        var dummyStyle = document.createElement('div').style;
        var vendors = 't,webkitT,MozT,msT,OT'.split(','),
            t,
            i = 0,
            l = vendors.length;
        var temp = null;
        for (; i < l; i++) {
            t = vendors[i] + 'ransform';
            if (t in dummyStyle) {
                temp = vendors[i].substr(0, vendors[i].length - 1);
                break;
            }
        }
        if (temp && temp == "") {
            return false;
        } else {
            return true;
        }
    };

    IScrollList.prototype.showNoData = function() {
        var $noDataView = $("<div>暂无数据</div>");
        $noDataView.css({
            "position": "absolute",
            "top": "0",
            "left": "0",
            "line-height": this.$container.height() + "px",
            "text-align": "center",
            "width": "100%",
            "font-size": "2rem",
            "height": this.$container.height() + "px"
        });
        this.$html.html($noDataView);
    };

    IScrollList.prototype.scrollToTop = function() {
        this.myScroll.scrollToElement(this.$content.children().first().get(0), 0);
    };

    return IScrollList;
});
